package com.jyniubi.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jyniubi.base.exception.Assert;
import com.jyniubi.base.result.R;
import com.jyniubi.base.result.ResponseEnum;
import com.jyniubi.base.utils.JwtUtils;
import com.jyniubi.core.enums.UserBindEnum;
import com.jyniubi.core.hfb.FormHelper;
import com.jyniubi.core.hfb.HfbConst;
import com.jyniubi.core.hfb.RequestHelper;
import com.jyniubi.core.pojo.entity.UserBind;
import com.jyniubi.core.pojo.entity.UserInfo;
import com.jyniubi.core.service.UserBindService;
import com.jyniubi.core.service.UserInfoService;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.User;
import org.apache.http.util.Asserts;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 前端控制器
 * </p>
 *
 * @author jyzhang
 * @since 2024-04-27
 */
@RestController
@RequestMapping("/api/core/userBind")
public class ApiUserBindController {
    private static String SUCCESS = "success";
    private static String FAIL = "fail";
    @Resource
    UserBindService userBindService;
    @Resource
    UserInfoService userInfoService;
    @ApiOperation("hfb绑定后回调")
    @PostMapping("/notify")
    public String notifyUrl(HttpServletRequest request){
        // 获取hfb返回的绑定结果
        Map<String, Object> map = RequestHelper.switchMap(request.getParameterMap());
        // 验签
        boolean signEquals = RequestHelper.isSignEquals(map);
        if (!signEquals){
            return FAIL;
        }
        // hfb业务处理是否成功
        String resultCode = map.get("resultCode").toString();
        if (resultCode ==null || !"0001".equals(resultCode)){
            return FAIL;
        }
        // 绑定成功，将数据存入表中
        String agentUserId = map.get("agentUserId").toString();
        String bindCode = map.get("bindCode").toString();
        // 根据userId先把数据查出来，然后再更新
        UserBind userBind = userBindService.getOne(Wrappers.lambdaQuery(UserBind.class)
                .eq(UserBind::getUserId, agentUserId));
        // 更新userBind表
         userBindService.update(Wrappers.lambdaUpdate(UserBind.class)
                .eq(UserBind::getUserId,agentUserId)
                .set(UserBind::getBindCode,bindCode)
                .set(UserBind::getStatus,UserBindEnum.BIND_OK.getStatus()));
        // 更新userInfo表
        userInfoService.update(Wrappers.lambdaUpdate(UserInfo.class)
                .eq(UserInfo::getId,agentUserId)
                .set(UserInfo::getBindCode,bindCode)
                .set(UserInfo::getBindStatus,UserBindEnum.BIND_OK.getStatus())
                .set(UserInfo::getName,userBind.getName())
                .set(UserInfo::getIdCard,userBind.getIdCard()));
        return SUCCESS;
    }


    @ApiOperation("账户绑定")
    @PostMapping("/auth/hfbBind")
    public R hfbBind(@RequestBody UserBind userBind, @RequestHeader("token") String token) {
        Long userId = JwtUtils.getUserId(token);
        // 判断用户是否已经绑定过汇付保
        int count = userBindService.count(Wrappers.lambdaQuery(UserBind.class)
                .eq(UserBind::getUserId, userId)
                .eq(UserBind::getStatus, UserBindEnum.BIND_OK));
        Assert.assertTrue(count >0, ResponseEnum.USER_BIND_IDCARD_EXIST_ERROR);
        //调用工具类将参数封装为自动提交的表单字符串响应
        Map<String,Object> map = new HashMap<>();
        map.put("agentId", HfbConst.AGENT_ID);
        map.put("agentUserId",userId);
        map.put("idCard",userBind.getIdCard());
        map.put("personalName",userBind.getName());
        map.put("bankType",userBind.getBankType());
        map.put("bankNo",userBind.getBankNo());
        map.put("mobile",userBind.getMobile());
        map.put("returnUrl",HfbConst.USERBIND_RETURN_URL);
        map.put("notifyUrl",HfbConst.USERBIND_NOTIFY_URL);
        map.put("timestamp",System.currentTimeMillis());
        String sign = RequestHelper.getSign(map);
        map.put("sign",sign);
        String form = FormHelper.buildForm(HfbConst.USERBIND_URL, map);
        //保存用户绑定账户的数据
        userBind.setUserId(userId);
        userBind.setStatus(UserBindEnum.NO_BIND.getStatus());
        userBindService.save(userBind);
        return R.ok().data("form",form);
    }
}

